
(function() {
    "use strict";

    // custom scrollbar

    $("html").niceScroll({styler:"fb",cursorcolor:"#65cea7", cursorwidth: '6', cursorborderradius: '0px', background: '#424f63', spacebarenabled:false, cursorborder: '0',  zindex: '1000'});

    $(".left-side").niceScroll({styler:"fb",cursorcolor:"#65cea7", cursorwidth: '3', cursorborderradius: '0px', background: '#424f63', spacebarenabled:false, cursorborder: '0'});


    $(".left-side").getNiceScroll();
    if ($('body').hasClass('left-side-collapsed')) {
        $(".left-side").getNiceScroll().hide();
    }



    // Toggle Left Menu
   jQuery('.menu-list > a').click(function() {
      
      var parent = jQuery(this).parent();
      var sub = parent.find('> ul');
      
      if(!jQuery('body').hasClass('left-side-collapsed')) {
         if(sub.is(':visible')) {
            sub.slideUp(200, function(){
               parent.removeClass('nav-active');
               jQuery('.main-content').css({height: ''});
               mainContentHeightAdjust();
            });
         } else {
            visibleSubMenuClose();
            parent.addClass('nav-active');
            sub.slideDown(200, function(){
                mainContentHeightAdjust();
            });
         }
      }
      return false;
   });

   function visibleSubMenuClose() {
      jQuery('.menu-list').each(function() {
         var t = jQuery(this);
         if(t.hasClass('nav-active')) {
            t.find('> ul').slideUp(200, function(){
               t.removeClass('nav-active');
            });
         }
      });
   }

   function mainContentHeightAdjust() {
      // Adjust main content height
      var docHeight = jQuery(document).height();
      if(docHeight > jQuery('.main-content').height())
         jQuery('.main-content').height(docHeight);
   }

   //  class add mouse hover
   jQuery('.custom-nav > li').hover(function(){
      jQuery(this).addClass('nav-hover');
   }, function(){
      jQuery(this).removeClass('nav-hover');
   });


   // Menu Toggle
   jQuery('.toggle-btn').click(function(){
       $(".left-side").getNiceScroll().hide();
       
       if ($('body').hasClass('left-side-collapsed')) {
           $(".left-side").getNiceScroll().hide();
       }
      var body = jQuery('body');
      var bodyposition = body.css('position');

      if(bodyposition != 'relative') {

         if(!body.hasClass('left-side-collapsed')) {
            body.addClass('left-side-collapsed');
            jQuery('.custom-nav ul').attr('style','');

            jQuery(this).addClass('menu-collapsed');

         } else {
            body.removeClass('left-side-collapsed chat-view');
            jQuery('.custom-nav li.active ul').css({display: 'block'});

            jQuery(this).removeClass('menu-collapsed');

         }
      } else {

         if(body.hasClass('left-side-show'))
            body.removeClass('left-side-show');
         else
            body.addClass('left-side-show');

         mainContentHeightAdjust();
      }

   });
   

   searchform_reposition();

   jQuery(window).resize(function(){

      if(jQuery('body').css('position') == 'relative') {

         jQuery('body').removeClass('left-side-collapsed');

      } else {

         jQuery('body').css({left: '', marginRight: ''});
      }

      searchform_reposition();

   });

   function searchform_reposition() {
      if(jQuery('.searchform').css('position') == 'relative') {
         jQuery('.searchform').insertBefore('.left-side-inner .logged-user');
      } else {
         jQuery('.searchform').insertBefore('.menu-right');
      }
   }

    // panel collapsible
	$(document).on("click",".panel .tools .fa",function(){
   // $('.panel .tools .fa').click(function () {
        var el = $(this).parents(".panel").children(".panel-body");
        if ($(this).hasClass("fa-chevron-down")) {
            $(this).removeClass("fa-chevron-down").addClass("fa-chevron-up");
            el.slideUp(200);
        } else {
            $(this).removeClass("fa-chevron-up").addClass("fa-chevron-down");
            el.slideDown(200); }
    });

	$(document).on("click",".todo-check label",function(){
        $(this).parents('li').children('.todo-title').toggleClass('line-through');
    });

    $(document).on('click', '.todo-remove', function () {
        $(this).closest("li").remove();
        return false;
    });

    $("#sortable-todo").sortable();


    // panel close
    $('.panel .tools .fa-times').click(function () {
        $(this).parents(".panel").parent().remove();
    });



    // tool tips

    $('.tooltips').tooltip();

    // popovers

    $('.popovers').popover();

		//菜单点击
	$(".sub-menu-list li a.open_sub_menu").click(function(e){
		if ($(this).hasClass("active")){
			$(this).removeClass("active");
			$(this).siblings("ul").hide();
		}else{
			$(this).parent("li").parent("ul").children("li").children("ul.sub-menu-list").hide();
			$(this).parent("li").parent("ul").children("li").children("a.open_sub_menu").removeClass("active");
			$(this).addClass("active");
			$(this).siblings("ul").show();
		}	
	});

})(jQuery);




//------------------------------页面表格查询js------------------------------
var table_th=new Array();



function ReloadTableTh(){
	$(".table_store thead th").each(function(i, n) {
		if($(n).text()=='序号')
			return true;
		var obj=new Object();
		obj.id=i;
		obj.name=$(n).attr("column");
		obj.th_name=delHtmlTag($(n).text());
		obj.option="";
		obj.is_show=true;
		obj.order_id=i;
		table_th.push(obj);
	});
}

//保存筛选条件到li上和table_th数组内
function save_option_val(){

	var li_id=$("#option_edit").attr("li_id");
	var select_1=$(".select_val_1").val();
	var select_2=$(".select_val_2").val();
	var input_1=$.trim($(".select_val_1_text").val());
	var input_2=$.trim($(".select_val_2_text").val());
	var radio_1=$("input[name='optionsRadios']:checked").val();
	var check_result={"select_1":"","input_1":"","radio_1":"","select_2":"","input_2":""};

		 check_result.select_1=select_1;
		 check_result.input_1=input_1;
		 check_result.radio_1=radio_1;
		 check_result.select_2=select_2;
		 check_result.input_2=input_2;
		 
	if ((select_1!="in" &&  select_1!="nn" && input_1!="") || (select_2!="in" &&  select_2!="nn" && input_2!="") || select_1=="in" || select_1=="nn" || select_2=="in" || select_2=="nn"){
			$("li[value='"+li_id+"'] input:hidden").val(JSON.stringify(check_result)); 
			table_th[li_id].option=JSON.stringify(check_result);
		}else{
			$("li[value='"+li_id+"']").attr("option_val","");
			table_th[li_id].option="";
	}
	check_li_selected();
}


//检测筛选条件是否有效，并还原筛选条件选框
function check_li_selected(){
	$(".select_li li").each(function(i,n) {
	    if ($.trim($(n).children("input").val())==""){
			$(n).removeClass("selected");	
		}else{
			$(n).addClass("selected");
		}
  });
}

//读取li上的条件筛选值并赋值
function set_option_val(str){
	obj=$.parseJSON(str); 
	$(".select_val_1 option[value='"+obj.select_1+"']").prop("selected",true);
	$(".select_val_2 option[value='"+obj.select_2+"']").prop("selected",true);
	$(".select_val_1_text").val(obj.input_1);
	$(".select_val_2_text").val(obj.input_2);
	$("input[name='optionsRadios'][value='"+obj.radio_1+"']").prop('checked',true);
}
//转条件名称
function select_option_name(str){
	switch (str)
	   {
	   case "lk":
		 str="相似";
		 break;
	   case "nk":
		str="不相似";
		 break;
	   case "eq":
		str="等于";
		 break;
	   case "ne":
		str="不等于";
		 break;
	   case "lt":
		str="小于";
		 break;
	   case "le":
		str="小于等于";
		 break;
	   case "gt":
		str="大于";
		 break;
	   case "ge":
		str="大于等于";
		 break;
	   case "in":
		str="为空";
		 break;
	    case "nn":
		str="不为空";
		 break;
		 case "and":
		str="并且";
		 break;
		 case "or":
		str="或者";
		 break;
	}
	return str;
}
//筛选条件转为中文
function option_to_str(option){
	option=$.parseJSON(option);
	var select_1=option.select_1;
	var select_2=option.select_2;
	var input_1=option.input_1;
	var input_2=option.input_2;
	var radio_1=option.radio_1;
	var str="";
	var str2="";
	//{"select_1":"nk","input_1":"12","radio_1":"or","select_2":"eq","input_2":"23"}
	//if ((select_1!="in" &&  select_1!="nn" && input_1!="") || (select_2!="in" &&  select_2!="nn" && input_2!="") || select_1=="in" || select_1=="nn" || select_2=="in" || select_2=="nn"){
	if (select_1=="in" || select_1=="nn"){
		str= select_option_name(select_1);
	}else if( input_1!=""){
		str=select_option_name(select_1)+input_1;
	}
	
	if (select_2=="in" || select_2=="nn"){
		str2=select_option_name(select_2);
	}else if( input_2!=""){
		str2=select_option_name(select_2)+input_2;
	}
	
	if(str!="" && str2!=""){
		return str+select_option_name(radio_1)+str2;
	} else{
		return str+str2;
	}
}

//js去掉所有html标记的函数： 
function delHtmlTag(str){
	return str.replace(/<[^>]+>/g,"");//去掉所有的html标记
}



$(document).ready(function(e) {
	//筛选条件激活
	$(document).on("click",".option_check_list span",function(e){
		 
		if ($(this).hasClass("active"))
		{
			$(this).attr("class","btn btn-default btn-xs");
		}
		else{
			$(this).attr("class","btn btn-info btn-xs active");
		}
	});
	//删除单个筛选条件
	$(document).on("click",".option_check_list span i.fa-times",function(e){
		e.stopPropagation();
		var id=$(this).parent().attr("li_id");
		$("#table_th_list li[value='"+id+"']").removeClass("selected");
		$("#table_th_list li[value='"+id+"']").children("input").val("");
		$(this).parent("span").popover("destroy");
		$(this).parent("span").remove();
		table_th[id].option="";
		if ($(".option_check_list span").size()==0){
			$("#remove_all_span").remove();
		}
	});
	//删除所有筛选条件
	$(document).on("click","#remove_all_span",function(){
		$("#table_th_list li").removeClass("selected");
		$("#table_th_list li").children("input").val("");
		$(this).siblings("span").popover("destroy");
		$(this).siblings("span").remove();
		$(this).remove();
		$.each(table_th,function(i,n){
			n.option="";
		});
	});
	
	//搜索列检索
	$(document).on("keyup","#search_option_li",function(){
		if ($.trim($(this).val())!=""){
			$("#table_th_list li").hide();
			$("#table_th_list li:contains('"+$.trim($(this).val())+"')").show();
		}else{
			$("#table_th_list li").show();
		}
	});
	  
	/*
	$(document).on("show.bs.modal","#paramsSelect",function(){
		$("#table_th_list").html("");
		table_th=[];
		$("#table_show thead th").each(function(i, n) {
			var column = $(n).attr("data-column") ;
			if (column!=undefined&&column!='index_id'){
				table_th.push('{"id":"'+i+'","name":"'+$(n).attr("data-column")+'","th_name":"'+delHtmlTag($(n).text())+'","option":""}');
				$("#table_th_list").append('<li value="'+i+'" option_val="">'+$(n).text()+'</li>');	
			}
	    });
	});
	*/
	$(document).on("shown.bs.modal","#paramsSelect",function(){ 
		
		//生成筛选条件列表
		if($("#table_th_list").children().size()>0)
			return;
		ReloadTableTh();
		$.each(table_th,function(i, n) {
			if (n.option!=""){ 
				$("#table_th_list").append('<li value="'+n.id+'" clas="selected" ><input type="hidden" value=""/>'+n.th_name+'</li>');
				$("#table_th_list li[value='"+n.id+"']").children("input").val(n.option);
			}else{
				$("#table_th_list").append('<li value="'+n.id+'" ><input type="hidden" value=""/>'+n.th_name+'</li>');
			}	
	   });
		check_li_selected();
	});
	
	
	//弹出框关闭时生成筛选条件
	$(document).on("hidden.bs.modal","#paramsSelect",function(){
		
	 	$(".option_check_list").html("");
		var add_btn=false;
		$("#table_th_list li").each(function(i,n) {
          	var option=$(n).children("input").val();
				var name=$(n).text();
				var li_id=$(n).attr("value");
				if (option!=""){
					add_btn=true;
					$(".option_check_list").append(' <span class="btn btn-info btn-xs active" li_id="'+ li_id+'"  data-toggle="popover" title="'+name+'" data-content="'+option_to_str(option)+'">'+name+' <i class="fa fa-times"></i></span>');
					
				}
      });
		if (add_btn){$(".option_check_list").append(' <button class="btn btn-danger btn-xs" id="remove_all_span"><i class="fa fa-times"></i> 清除筛选</button>');}
		
		$('[data-toggle="popover"]').popover({"trigger":"hover","placement":"bottom"});
	});
	

	//筛选条件修改时生成触发保存值
	$(document).on("change","#option_edit input",function(){ 
			save_option_val();
	});
	$(document).on("change",".select_val_1",function(){
			save_option_val();
	});
	
	//列筛选条件点击
	$(document).on("click","#table_th_list li",function(){
			$("#option_edit input").prop("disabled",false);
			$("#option_edit select").prop("disabled",false); 
			$("#option_edit h4").html($(this).text()).show();
			check_li_selected();
			$("#option_edit").attr("li_id",$(this).attr("value"));
			$(this).addClass("selected");
			var option_val=$.trim($(this).children("input").val());
			$("#option_edit input[type='text']").val("");
			$("select.select_val_2").children("option:first").prop("selected",true);
			$("select.select_val_1").children("option:first").prop("selected",true);
		 	if (option_val!=""){ 
				set_option_val(option_val);
			} 
	})
	
	
	
});
//------------------------------页面表格拖拽js------------------------------

//保存table_th到localStorage
function save_cookie(){
	var tableID = $(".table_store").attr("id");
	var sortArray = [];
	$(".table_store thead tr th").each(function(i,n){
		sortArray.push($(n).attr("column"));
	});
	localStorage[tableID]=JSON.stringify(sortArray);
	
}

//更换两列位置index_1移动到index_2后面
function reset_index(index_1,index_2){
	//往前移和后移判断
	if (index_1<index_2){
		$(".table_store thead tr th:eq("+index_2+")").after($(".table_store thead tr th:eq("+index_1+")").clone());
		$(".table_store thead tr th:eq("+index_1+")").remove();
		$(".table_store tbody tr").each(function(i, n) {
		   $(n).children("td:eq("+index_2+")").after( $(n).children("td:eq("+index_1+")").clone());
		   $(n).children("td:eq("+index_1+")").remove();	
		});	
	}
	else{
		$(".table_store thead tr th:eq("+index_2+")").after($(".table_store thead tr th:eq("+index_1+")").clone());
		$(".table_store thead tr th:eq("+(parseInt(index_1)+1)+")").remove();	
		$(".table_store tbody tr").each(function(i, n) {
		   $(n).children("td:eq("+index_2+")").after( $(n).children("td:eq("+index_1+")").clone());
		   $(n).children("td:eq("+(parseInt(index_1)+1)+")").remove();	
		});	
	}
	//根据tabel的新th,生成排序
	$(".table_store thead th").each(function(i, n) {
			for (var j=0;j<table_th.length;j++){  
				if (table_th[j].name==$(n).attr("column")){
						table_th[j].order_id=i;
						break;
				}
			}
	});	
	move_th();
	$(".table_store thead tr th").css("left","auto").removeClass("active");
	save_cookie();
}

//绑定头部拖拽
function move_th(){
	$( ".table_store thead tr th" ).draggable({ 
		axis: "x",
		containment: "parent",
		scroll: true,
		scrollSpeed: 100,
		cursor: "move",
		start: function() {
			$(this).css("z-index",1);
			move_th_val=$(this).index();
		},
		drag: function() {
			$(this).addClass("active");
		},
		stop: function() {
			$(this).css("z-index","auto").removeClass("active");
			move_th_val="";
			
		}
	});
	$( ".table_store thead tr th" ).droppable({
		  hoverClass: "active",
		  drop: function() {
				//更换两列位置
				reset_index(move_th_val,$(this).index());	
				$("body").css("cursor","default"); 
		  }
	});
	
	var tableID=$(".table_store").attr("id");
	if(localStorage[tableID+"_hidden"]!=undefined){
		var hiddenCol = $.parseJSON(localStorage[tableID+"_hidden"]);
		//隐藏已选定隐藏列
		$.each(hiddenCol,function(i,n){
			hide_column_by_id(n);
		})
	}
		
}


//读取table_th,生成新的table
function reload_table(){

	setTimeout(function(){
		var tableID = $(".table_store").attr("id");
		if(localStorage[tableID]==undefined){
			move_th();
			return;
		}
		var new_table_thead=new Array();
		var new_table_tbody = new Array();  
		
		//生成tbody的二维数组
		for(var k=0;k<$(".table_store thead tr th").size();k++){
		 new_table_tbody[k]=new Array(); 
			for(var j=0;j<$(".table_store tbody tr").length;j++){ 
			  new_table_tbody[k][j]=""; 
			 }
		}
		//根据table_th保存值生成新的tbody和thead
		
		var sortArray=$.parseJSON(localStorage[tableID]);
		for(var i=0,j=sortArray.length;i<j;i++){
			var th = $("th[column='"+sortArray[i]+"']");
			new_table_thead.push('<th column="'+sortArray[i]+'">'+th.text()+'</th>')
			
			$(".table_store tbody tr").each(function(j,m) {
				new_table_tbody[j][i]='<td>'+$(m).children("td:eq("+th.index()+")").html()+'</td>';
			});
		}
		
		//生成新的table html代码
		var table_head_str='<tr>'+new_table_thead.join("")+'</tr>';
		var table_tbody_str='';
		$.each(new_table_tbody,function(i,n){
			table_tbody_str+='<tr>'+n.join("")+'</tr>';
		})
		
		$(".table_store thead").html(table_head_str);
		$(".table_store tbody").html(table_tbody_str);
		
		move_th();
		
	},100);
	
	
}
//隐藏某列
function hide_column_by_id(id){
	var th = $(".table_store thead tr th[column='"+id+"']");
	var index = $(".table_store thead tr th[column='"+id+"']").index();
	th.hide();
	$(".table_store tbody tr").each(function(i,n) {
        $(n).children("td").eq(index).hide();
    });
}

$(document).ready(function() {

	 //显示列显示控制窗口
	 $(document).on("click",".col_show_list i",function(){
			show_th_checkbox()
			$(this).siblings("ul").toggle();
	 })
	 
	  $(document).on("click","body",function(e){	  
		if (!$(e.target).parents(".col_show_list").hasClass("col_show_list")){
			$(".col_show_list ul").hide();
		}	 
	 })
	 $(document).on("click",".col_show_list input",function(e){
			var input = $(e.target);
			if(input.attr("checked")==undefined){
				hide_column_by_id(input.val());
			}else{
				show_column_by_id(input.val());
			}
			resetColHidden();
	 })
	 function resetColHidden(){
		 var tableID = $(".table_store").attr("id");
		 var colArr = [];
		 $.each($(".col_show_list input"),function(i,n){
			 if($(n).attr("checked")==undefined){
				 	colArr.push(n.value); 
			 }
		 });
		 localStorage[tableID+"_hidden"]=JSON.stringify(colArr);
	 }
	//显示某列
	 function show_column_by_id(id){
	 	var th = $(".table_store thead tr th[column='"+id+"']");
	 	var index = $(".table_store thead tr th[column='"+id+"']").index();
	 	th.show();
	 	$(".table_store tbody tr").each(function(i,n) {
	         $(n).children("td").eq(index).show();
	     });
	 }
	
	 //生成列显示控制窗口
	 function show_th_checkbox(){
	  	var li_list=new Array();
	 	$.each($(".table_store thead tr th"),function(i,n){
	 		var column = $(n).attr("column");
	 		var name = $(n).text();
	 		if (!colContains(column))
	 		{
	 			li_list.push('<li><input type="checkbox" value="'+column+'" checked>'+name+'</li>');	
	 		}else{
	 			li_list.push('<li><input type="checkbox" value="'+column+'" >'+name+'</li>');
	 		}	
	 	})
	 	$(".col_show_list ul").html(li_list.join(""));
	 }
	 
	 function colContains(column){
		 var tableID = $(".table_store").attr("id");
		 var flag = false;
		 if(localStorage[tableID+"_hidden"]!=undefined){
				var hiddenCol = $.parseJSON(localStorage[tableID+"_hidden"]);
				$.each(hiddenCol,function(i,n){
					if(n==column)
						flag= true;
				});
		 }
		 return flag;
	 }
})


